﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using LOGISTCBUS.Entities;
using LOGISTCBUS.DAO;

namespace LOGISTCBUS.WebUI.Controllers
{
    [HandleError(View = "Error")]
    public class CostController : Controller
    {
        public ActionResult Index()
        {
            var user = (User)this.Session["user"];
            if (user == null)
                return RedirectToAction(@"LogOut", @"Account");
            return View();
        }

        public ActionResult Edit(int? id)
        {
            var userLogged = (User)this.Session["user"];
            if (userLogged == null)
                return RedirectToAction(@"LogOut", @"Account");

            if (id.HasValue)
            {
                var cost = new CostDAO().selectById(Convert.ToInt32(id));
                this.ViewData[@"cost"] = cost == null ? new Cost() : cost;
            }

            return View();
        }

        [AcceptVerbs(HttpVerbs.Post)]
        public JsonResult Save(int id)
        {
            var c = id > 0 ? new CostDAO().selectById(id) : new Cost();
            var aux = true;

            c.Employee = !String.IsNullOrEmpty(Request.Params["id_employee"]) ? new Employee() { Id = Convert.ToInt32(Request.Params["id_employee"]) } : null;
            c.CostType = !String.IsNullOrEmpty(Request.Params["id_cost_type"]) ? new CostType() { Id = Convert.ToInt32(Request.Params["id_cost_type"]) } : null;
            c.Trip = !String.IsNullOrEmpty(Request.Params["id_trip"]) ? new Trip() { Id = Convert.ToInt32(Request.Params["id_trip"]) } : null;
            c.Name = !String.IsNullOrEmpty(Request.Params["name"]) ? Request.Params["name"] : null;
            if (!String.IsNullOrEmpty(Request.Params["value"]))
                c.Value = Convert.ToDecimal(Request.Params["value"]);
            c.Variable = !String.IsNullOrEmpty(Request.Params["variable"]) ? Request.Params["variable"] : null;
            if (!String.IsNullOrEmpty(Request.Params["quantity"]))
                c.Quantity = Convert.ToInt32(Request.Params["quantity"]);
            c.Description = !String.IsNullOrEmpty(Request.Params["description"]) ? Request.Params["description"] : null;

            if (c.Id > 0)
                aux = new CostDAO().update(c);
            else
                aux = new CostDAO().insert(c);

            var obj = new
            {
                success = aux,
                message = "Despesa salva com sucesso!"
            };

            return Json(obj);
        }

        [AcceptVerbs(HttpVerbs.Post)]
        public JsonResult Search()
        {
            var page = String.IsNullOrEmpty(Request.Params[@"page"]) ? 1 : Convert.ToInt32(Request.Params[@"page"]);
            var name = String.IsNullOrEmpty(Request.Params[@"name"]) ? string.Empty : Request.Params[@"name"].ToString();
            var pageSize = MvcApplication.pageSize;
            var costs = new CostDAO().select(name, page, pageSize);
            var count = new CostDAO().getCount(name);
            var totalPages = (count < pageSize) ? 1 : Math.Ceiling(Convert.ToDecimal(count) / pageSize);
            var lst = new List<object>();

            foreach (var c in costs)
            {
                lst.Add(new
                {
                    Id = c.Id,
                    Name = c.Name,
                    Quantity = c.Quantity,
                    Value = String.Format("R$ {0:######0.00}", c.Value)
                });
            }

            var obj = new
            {
                data = lst,
                currpage = page,
                totalpages = totalPages,
                totalrecords = count
            };

            return Json(obj);
        }

        [AcceptVerbs(HttpVerbs.Post)]
        public JsonResult Delete()
        {
            var id = String.IsNullOrEmpty(Request.Params[@"id"]) ? 0 : Convert.ToInt32(Request.Params[@"id"]);
            var page = String.IsNullOrEmpty(Request.Params[@"page"]) ? 1 : Convert.ToInt32(Request.Params[@"page"]);
            var aux = true;

            if (id > 0)
            {
                var c = new Cost() { Id = id };
                aux = new CostDAO().delete(c);
            }

            var obj = new
            {
                Message = "Registro removido com sucesso!",
                Success = aux,
                Page = page
            };

            return Json(obj);
        }

        [AcceptVerbs(HttpVerbs.Post)]
        public JsonResult DeleteAll()
        {
            var values = Request.Form["ids"].Split(new String[] { ";" }, StringSplitOptions.RemoveEmptyEntries);
            var aux = true;

            var lst = new List<Cost>();
            foreach (var val in values)
                if (!String.IsNullOrEmpty(val))
                    lst.Add(new Cost() { Id = Convert.ToInt32(val) });
            aux = new CostDAO().delete(lst);

            var obj = new
            {
                Message = "Registro(s) removido(s) com sucesso!",
                Success = aux
            };

            return Json(obj);
        }

        [AcceptVerbs(HttpVerbs.Post)]
        public JsonResult GetCostType()
        {
            var idType = String.IsNullOrEmpty(Request.Params[@"idType"]) ? 0 : Convert.ToInt32(Request.Params[@"idType"]);
            var costType = new CostTypeDAO().selectById(idType);

            var obj = new
            {
                Value = costType != null ? String.Format("{0:######0.00}", costType.Value) : String.Format("{0:######0.00}", Decimal.Zero)
            };

            return Json(obj);
        }
    }
}
